package com.tuanzi.loan.business.service.statistics.impl;

import com.tuanzi.loan.business.repository.statistics.LoanHitLibraryResultRepository;
import com.tuanzi.loan.business.repository.statistics.StatHitSuccessRepository;
import com.tuanzi.loan.business.service.statistics.StatHitSuccessService;
import com.tuanzi.loan.core.aspect.Debug;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.jooq.Record;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.tuanzi.loan.generated.jooq.loan.tables.LoanHitLibraryResult.LOAN_HIT_LIBRARY_RESULT;


/**
 * @author Simon
 * @date 2019/08/02 15:58
 */
@Slf4j
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class StatHitSuccessServiceImpl implements StatHitSuccessService {
    @Autowired
    private LoanHitLibraryResultRepository loanHitLibraryResultRepository;
    @Autowired
    private StatHitSuccessRepository stathitsuccessRepository;

    @Override
    public void stat(String time) throws ParseException {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isBlank(time)) {
            time = DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00");
            date = simpleDateFormat.parse(time);
        } else {
            date = simpleDateFormat.parse(time);
        }

        task(date);

    }

    private void task(Date day) {

        // 当天撞库人数
        log.info("每日新老用户撞库统计时间:{}",day);
        Map<String, List<Record>> hitUserMapping = loanHitLibraryResultRepository.findAllByDate(day).stream().peek(x -> {
            if (StringUtils.isBlank(x.get(LOAN_HIT_LIBRARY_RESULT.PLATFORM)) && StringUtils.isNotBlank(x.get(LOAN_HIT_LIBRARY_RESULT.PHONEID))) {
                x.set(LOAN_HIT_LIBRARY_RESULT.PLATFORM, StringUtils.length(x.get(LOAN_HIT_LIBRARY_RESULT.PHONEID)) > 24 ? "ios" : "android");
            }
            x.set(LOAN_HIT_LIBRARY_RESULT.PLATFORM, StringUtils.isBlank(x.get(LOAN_HIT_LIBRARY_RESULT.PLATFORM)) ? "-1" : x.get(LOAN_HIT_LIBRARY_RESULT.PLATFORM));
            x.set(LOAN_HIT_LIBRARY_RESULT.CHANNEL, x.get(LOAN_HIT_LIBRARY_RESULT.CHANNEL) == null ? -1 : x.get(LOAN_HIT_LIBRARY_RESULT.CHANNEL));
            x.set(LOAN_HIT_LIBRARY_RESULT.PRODUCT_ID, StringUtils.isBlank(x.get(LOAN_HIT_LIBRARY_RESULT.PRODUCT_ID)) ? "-1" : x.get(LOAN_HIT_LIBRARY_RESULT.PRODUCT_ID));
            x.set(LOAN_HIT_LIBRARY_RESULT.HIT_LIB_TYPE, x.get(LOAN_HIT_LIBRARY_RESULT.HIT_LIB_TYPE) == null ? -1 : x.get(LOAN_HIT_LIBRARY_RESULT.HIT_LIB_TYPE));
            x.set(LOAN_HIT_LIBRARY_RESULT.IS_NEW_USER, x.get(LOAN_HIT_LIBRARY_RESULT.IS_NEW_USER) == null ? (byte) -1 : x.get(LOAN_HIT_LIBRARY_RESULT.IS_NEW_USER));

        }).collect(Collectors.groupingBy(x -> StringUtils.join(new String[] { x.get(LOAN_HIT_LIBRARY_RESULT.PLATFORM), x.get(LOAN_HIT_LIBRARY_RESULT.CHANNEL).toString(), x.get(LOAN_HIT_LIBRARY_RESULT.PRODUCT_ID),
                x.get(LOAN_HIT_LIBRARY_RESULT.HIT_LIB_TYPE).toString(), x.get(LOAN_HIT_LIBRARY_RESULT.IS_NEW_USER).toString() }, ":")));

        // 遍历新增Mapping
        log.info("每日新老用户撞库统计size：{},time: {}" , hitUserMapping.size(), new Date());
        for (Map.Entry<String, List<Record>> entry : hitUserMapping.entrySet()) {

            String[] parameters = StringUtils.split(entry.getKey(), ":");
            String platform = parameters[0];
            String channel = parameters[1];
            String prdId = parameters[2];
            String hitLirType = parameters[3];
            String new_user = parameters[4];

            List<Record> newUsers = entry.getValue();// 新增list

            try {
                stathitsuccessRepository.saveOrUpdate(platform, prdId, channel, new_user, day, hitLirType, CollectionUtils.size(newUsers));
            }catch (Exception e){

                log.error("update撞库统计记录出错：{}", e.getMessage(),platform, prdId, channel, new_user, day, hitLirType, CollectionUtils.size(newUsers));
            }
        }
        log.info("hit:success: {}",day);
    }

}
